<?php
/**
 * Created by jinqiang on 2024/9/12 11:12.
 * Copyright (c) 2024, Your Company. All rights reserved.
 */


namespace App\Http\Services\Soa;


use App\Http\Models\Mysql\SsyFeishuApprovalBindingTable;
use App\Http\Models\Mysql\SsyFineAmountTable;
use App\Http\Models\Mysql\SsyFlowWfRunTable;
use App\Http\Models\Mysql\SsyJyProductListTable;
use App\Http\Models\Mysql\SsyProcessingFactoryNameTable;
use App\Http\Models\Mysql\SsyProcessingListTable;
use App\Http\Repository\ApprovalRepository;
use App\Http\Repository\FeishuRepository;

class FineService
{
    public function search($param)
    {
        $conn = (new SsyFineAmountTable());
        if($param['processing_code'] ?? ""){
            $conn = $conn->where('processing_code', 'like', $param['processing_code']."%");
        }
        if($param['factory_contract_no'] ?? ""){
            $conn = $conn->where('factory_contract_no', 'like', $param['factory_contract_no']."%");
        }
        if($param['type_no'] ?? ""){
            $conn = $conn->where('type_no', 'like', $param['type_no']."%");
        }
        if($param['supplier_id'] ?? ""){
            $conn = $conn->where('supplier_id', $param['supplier_id']);
        }
        if(isset($param['k_status']) && $param['k_status'] != ''){
            $kStatus = (Int)$param['k_status'];
            $conn = $conn->whereIn('k_status', $kStatus == 0 ? [0, 1] : [2]);
        }
        if(isset($param['status']) && $param['status'] != ''){
            $conn = $conn->where('status', (Int)$param['status']);
        }
        $res = $conn->orderBy("createtime", "desc")->paginate((Int)$param['limit'])->toArray();
        $ids = array_column($res['data'], 'id');
        $runMap = [];
        if(!empty($ids)){
            $runList = (new SsyFeishuApprovalBindingTable())->whereIn('data_id', $ids)->where('types', 21)->get(['data_id', 'instance_code'])->toArray();
            $runMap = array_column($runList, 'instance_code', 'data_id');
        }
        foreach ($res['data'] as &$item){
            $images = !empty($item['images']) ? unserialize($item['images']) : "";
            $item['run_id'] = $runMap[$item['id']] ?? "";
            $item['images'] = isset($images[0]['url']) ? array_column($images, 'url') : $images;
            $item['remarks'] = str_replace("\n", "<br>", $item['remarks']);
        }
        unset($item);
        return ['data' => $res['data'], 'total' => $res['total']];
    }

    public function approvalProcess($param)
    {
        //获取审批数据
        $obj = (new SsyFineAmountTable())->where('id', (Int)$param['id'])->first()->toArray();
        $images = !empty($obj['images']) ? unserialize($obj['images']) : "";
        $obj['images'] = isset($images[0]['url']) ? array_column($images, 'url') : $images;
        $obj['price_list'] = [
            [
                'type_no' => $obj['type_no'],
                'reason' => $obj['reason'],
                'amount' => $obj['amount']
            ]
        ];
        //获取审批流程
        $user = auth()->guard("api")->user()->toArray();
        $flow = (new FeishuRepository($user['is_subject']))->getFlow($param['run_id']);
        return ['flow' => $flow, 'data' => $obj];
    }

    public function create($param)
    {
        $factoryObj = (new SsyProcessingFactoryNameTable())->where('supplier_id', $param['supplier_id'])->first(['factory_name']);
        $processingObj = (new SsyProcessingListTable())->where('type_no', $param['type_no'])->first(["processing_code","type_name"])->toArray();
        $data = [
            'factory_contract_no' => $param['factory_contract_no'],
            'factory_name' => $factoryObj->factory_name,
            'type_no' => $param['type_no'],
            'type_name' => $processingObj['type_name'],
            'reason' => $param['reason'],
            'amount' => $param['amount'],
            'remarks' => trim($param['remarks']),
            'adduser' => auth()->guard("api")->user()->name,
            'order_processor' => $param['order_processor'],
            'supplier_id' => $param['supplier_id'],
            'processing_code' => $processingObj['processing_code'],
            'images' => serialize($param['images']),
            'source_factory_groups_id' => $param['source_factory_groups_id'],
            'createtime' => date("Y-m-d H:i:s"),
        ];
        $user = auth()->guard("api")->user()->toArray();
        $subjectMap = array_column(config("scm.subject"), null, 'brand_code_jy');
        $subjects = array_column(config("scm.subject"), null, 'is_subject');
        $jyObj = (new SsyJyProductListTable())->where('product_code', "like", $param['type_no']."%")->first(['brand_code'])->toArray();
        $isSubject = $subjectMap[$jyObj['brand_code']]['is_subject'];
        $approvalSubject = in_array($isSubject, ['kz', 'mz', 'qyx']) ? 'kz' : $isSubject;
        $fsUserId = $user[$approvalSubject.'_feishu_user_id'];
        $fsOpenId = $user[$approvalSubject.'_feishu_open_id'];
        $fsApprovalCode = $subjects[$approvalSubject]['fine_approval_code'];
        //$fsApprovalCode = "F5EB882A-163C-4CCD-AB98-64829D57D435";//内部测试
        if(empty($fsApprovalCode)){
            return ['code' => -1, 'msg' => '当前主体未添加该审批流程'];
        }
        //费用信息
        $infoStr = '[{"id": "type_no","type":"input","value":"' .$data['type_no'].'"},{"id": "reason","type":"input","value":"'
            .$data['reason'].'"},{"id": "amount","type":"input","value":"' .$data['amount'].'"}]';
        //截图说明
        $imageStr = "";
        if(!empty($param['images'])){
            foreach ($param['images'] as $url){
                $upRes = (new FeishuRepository($user['is_subject']))->upload([
                    'name' => "违约金".$processingObj['processing_code'],
                    'type' => 'image',
                    'content' => $url
                ]);
                if($upRes['data']['code'] ?? ""){
                    $imageStr .= ','.'"'.$upRes['data']['code'].'"';
                }
            }
            $imageStr = ltrim($imageStr,",");
        }
        $subjectLabelMap = ["kz" => "mcn0qfz5-qz9vsmpyvue-0", "mz" => "mcn0qfz5-4urka5cxk0p-0", "qyx" => "mcn0qfz5-jeth3nh3qaj-0"];
        //品牌字段
        $brandStr = $approvalSubject == "kz" ? '{"id":"is_subject","type":"radioV2","value":"'.$subjectLabelMap[$isSubject].'"},' : "";
        $postData = [
            "approval_code" => $fsApprovalCode,
            "user_id" => $fsUserId,
            "open_id" => $fsOpenId,
            "form" => '['.$brandStr.'{"id":"factory_name","type":"input","value":"' .$data['factory_name'].'"},{"id":"factory_contract_no","type":"input","value":"'
                .$data['factory_contract_no'].'"},{"id": "info","type": "fieldList","value": ['.$infoStr.']},{"id":"remarks","type":"textarea","value":"'
                .$data['remarks'].'"},{"id":"image","type":"image","value":[' .$imageStr.']}]'
        ];
        $res = (new FeishuRepository($approvalSubject))->createApproval($postData);
        if($res['code'] != '0'){
            return ['code' => -1, 'msg' => '创建违约赔偿,失败!'.($res['msg'] ?? ""), 'data' => $res];
        }
        $createRes = (new SsyFineAmountTable())->createData($data);
        if($createRes['id'] ?? ""){
            return (new SsyFeishuApprovalBindingTable())->createData([
                "instance_code" => $res['data']['instance_code'],
                "data_id" => $createRes['id'],
                "types" => 21,
                "createtime" => date('Y-m-d H:i:s')
            ]);
        }
        return $createRes;
    }
}
